class UserController < ApplicationController

  before_filter :login_required, :only => :my_account

  def login
    @user = User.new
    @user.username = params[:username]
  end

  def process_login
    if user = User.authenticate(params[:user])
      #       #render :js => "alert('Invalid login');"
      session[:id] = user.id # Remember the user's id during this session
      redirect_to session[:return_to] || '/user/home'
    else
      flash[:error] = 'Invalid login.'
      redirect_to :action => 'login'
    end
  end

  def search
    @users = User.search params[:search]
  end

  def search_page
  end

  def logout
    reset_session
    flash[:message] = 'Logged out.'
    redirect_to :action => 'login'
  end
    
  def create_user
    @user = User.new(params[:user])
    if @user.save
      flash[:notice] = "Registration successful."
      redirect_to root_url
    else
      flash[:error] = 'Invalid account parameters.'
      redirect_to :action => 'create_account'
    end
  end
    
  def edit_user
    if @user.update_attributes(params[:user])
      flash[:notice] = 'Changes saved successfully.'
      redirect_to :action => 'edit_account'
    else
      flash[:error] = 'Error saving changes.'
      redirect_to :action => 'edit_account'
    end
  end
    
  def update_password
    if user.id == session[:id]
      User.update_password(params[:pass])
    end
  end
    
  def my_account
  end
    
  def create_account
  @user = User.new
  end
    
  def edit_account
  end
  
  def display
  	if @user.isAdmin == 1
  		redirect_to :action => 'show_admin', :id => params[:id]
  	else
  		redirect_to :action => 'show', :id => params[:id]
  	end
  end

  def show
	@person = User.find(params[:id])
  end
  
  def show_admin
  	if @user.isAdmin == 1
  		@person = User.find(params[:id])
  	else
      flash[:error] = 'Access Denied.'
      redirect_to :action => 'home'
  	end
  end
  
  def destroy
  	@person = User.find(params[:id])
  	if @user.isAdmin == 1 && @user.username != @person.username && @person.isAdmin != 1
  	  User.delete(params[:id])
  	  flash[:notice] = 'Delete Successful.'
  	  redirect_to :action => 'home'
  	else
      flash[:error] = 'Delete Failed.'
      redirect_to :action => 'home'
  	end
  end
  
  def promote
  	@person = User.find(params[:id])
  	if @user.isAdmin == 1 && @user.username != @person.username && @person.isAdmin != 1
  	  @person.isAdmin = 1
  	  if @person.save
  	  	flash[:notice] = 'User Promotion Successful.'
  	  	redirect_to :action => 'home'
  	  else
  	  	flash[:error] = 'Promotion Failed.'
        redirect_to :action => 'home'
  	  end
  	else
      flash[:error] = 'Promotion Failed.'
      redirect_to :action => 'home'
  	end
  end
end

